package mx.com.mindbits.bandpay.utils;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mx.com.mindbits.bandpay.vo.TAECompraVO;
import mx.com.mindbits.bandpay.vo.TAETransactionResponse;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

@SuppressLint("SimpleDateFormat")
public class Utils {
///////////////DEVICE FUNCTIONS////////////////	
	public static boolean isTablet(Context context){
		
		TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);	
        if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){
            return true;
        }else{
            return false;
        }
	}
	
	public static String getPhoneNumber(Context context){
		String telephoneNumber = "0000000000";
		TelephonyManager manager = (TelephonyManager)
				context.getSystemService(Context.TELEPHONY_SERVICE);
		try{
			
			if(!manager.getLine1Number().isEmpty()){
				telephoneNumber = manager.getLine1Number();
				Log.d(ConstantsValues.TAG_UTILS, " manager telefono: " + manager.getLine1Number());
			
				if (!telephoneNumber.isEmpty() || telephoneNumber != null){			
					Log.d(ConstantsValues.TAG_UTILS, "Numero de suscriptor: " +  manager.getSubscriberId());
					
					if(telephoneNumber.length()>10){
						telephoneNumber = telephoneNumber.substring(telephoneNumber.length()-10);
					}
				}			
			}
			Log.i(ConstantsValues.TAG_UTILS,"leer el numero de telefono del dis:" + manager.getLine1Number());
		}catch(Exception ex){
			Log.e(ConstantsValues.TAG_UTILS,"Error al leer el numero de telefono del dispositivo..." + ex);
		}
		
		Log.d(ConstantsValues.TAG_UTILS, "Numero de telefono: "+telephoneNumber);
		return telephoneNumber;				
	}
	
	public static boolean internetAvailable(Context context){
		boolean response = false;
		ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        
        if(wifi.isConnectedOrConnecting()){
        	response = true;
        }
        if (!isTablet(context)){
        	if(mobile.isConnectedOrConnecting()){
            	response = true;
            }
        }        
        
        return response;
	}
	
	public static  void startDevice( UsbManager managerUSB,
						 PendingIntent pendingIntent,
						Context context ) throws Exception{
		managerUSB = (UsbManager) context.getSystemService(Context.USB_SERVICE);	
		
		Log.d(ConstantsValues.TAG_READER, "Informacion del dispositivo: " + UsbManager.EXTRA_DEVICE);	
		
		HashMap<String,UsbDevice> deviceList = managerUSB.getDeviceList();
		
		Iterator<UsbDevice> iteratorDevice = deviceList.values().iterator();
		
		while(iteratorDevice.hasNext()){
			ConstantsValues.dispositivo = iteratorDevice.next();
		}		
	}
	
		
	public static void startDeviceWithoutAttach(Context context){
		
		UsbManager managerUsb = (UsbManager) context.getSystemService(Context.USB_SERVICE);

		Log.d(ConstantsValues.TAG_READER, "Informacion Utils extra Device: " + UsbManager.EXTRA_DEVICE);	
		
		HashMap<String,UsbDevice> deviceList = managerUsb.getDeviceList();
		Log.d(ConstantsValues.TAG_READER, "Informacion device list " + deviceList);
		Iterator<UsbDevice> iteratorDevice = deviceList.values().iterator();
		Log.d(ConstantsValues.TAG_READER, "tamanio de la lista Device: " + deviceList.size()
				
				);
		while(iteratorDevice.hasNext()){
			ConstantsValues.dispositivo = iteratorDevice.next();
			Log.d(ConstantsValues.TAG_READER, "Utils dispositivo: " + ConstantsValues.dispositivo);
		}//while
		
	}
	////////////////////////DATE ADN STRING FUNCTIONS///////////////////	
	public static String getYesterdayDate(){
		Date d = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24));
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		return sdf.format(d);
	}
	
	public static String getdayDate(){
		Date d = new Date(System.currentTimeMillis());
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
		return sdf.format(d);
	}
	
	//Get hour from device -v
	public static String getHourDate(){
		Calendar hour = Calendar.getInstance();
		
		SimpleDateFormat simpleHourFormat = new SimpleDateFormat("H:mm:ss");
		return simpleHourFormat.format(hour.getTimeInMillis());
	}
	
	public static String dateToString(Date dia){
		SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
		return sdf.format(dia);
	}
	
	public static Date stringToDate(String date){
		SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
		Date convertingDate = new Date();
		try{
			convertingDate = simpleDate.parse(date);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return convertingDate;
	}
	
	public static String cardNumberFormat(String cardNumber){
		String numberCard = "**** **** **** ****"; 
		if(cardNumber.length() > 0){
			int size = cardNumber.length();
			numberCard = "**** **** **** " + cardNumber.substring((size - 4), size);
		}
		
		return numberCard;
	}
	
	public static String cardExpirationDateFormated(String expirationDate){		
		String mes = "00";
		String anio = "00";
		mes = expirationDate.substring(2, 4);
		anio = expirationDate.substring(0,2);	
		return expirationDate = mes+"/"+anio;
	}
	
	public static String prosaDateFormated(String expirationDate){		
		String mes = "00";
		String anio = "00";
		mes = expirationDate.substring(2, 4);
		anio = expirationDate.substring(0,2);	
		return expirationDate = mes+anio;
	}
	
	public static String getCompanyLabel(String i){
		int j = Integer.parseInt(i);
		String response = "";
		switch(j){
		case 1:
			response = "IUSACEL";
			break;
		case 2:
			response = "MOVISTAR";
			break;
		case 3:
			response = "TELCEL";
			break;
		case 4:
			response = "UNEFON";
			break;
		default:
			response = ConstantsValues.LABEL_PAGO_GENERICO;
			break;
		}
		return response;
	}	
	
	 
	
	public static Double formatDouble(String doubleData){
		DecimalFormat format = new DecimalFormat("0.00");
		
		return Double.valueOf(format.format(Double.valueOf(doubleData)));
	}
	
	/**
	 * Method in order to set the float format
	 * @param 
	 *  
	 * */
	public static String setFloatFormat(float cantidad){
		
		DecimalFormatSymbols simbols = new DecimalFormatSymbols();
		simbols.setDecimalSeparator('.');
		simbols.setGroupingSeparator(',');
		DecimalFormat decimalFormat= new DecimalFormat("##,###.00",simbols);
		
		return decimalFormat.format(cantidad);
		
	}
	
	
	public static String setFloatFormatDecimal(float cantidad){
		
		DecimalFormatSymbols simbols = new DecimalFormatSymbols();
		simbols.setDecimalSeparator('.');
		DecimalFormat decimalFormat= new DecimalFormat(".##",simbols);
		
		return decimalFormat.format(cantidad);
		
	}
	public static double getDoubleFormatDecimal(String monto){
		double _monto = 0.0;		
			_monto = Double.valueOf(monto.replace(".", "").replace(",", ""));
			
		return _monto;
	}
	
	public static String getJSON(TAECompraVO compra) throws JSONException{
		JSONObject json = new JSONObject();
		
		json.put("afiliacion", compra.getAfiliacion());
		json.put("card", compra.getCard());
		json.put("cvv2",compra.getCvv2());
		json.put("cx", compra.getCx());
		json.put("cy", compra.getCy());
		json.put("iduser", compra.getIduser());
		json.put("imei", compra.getImei());
		json.put("login", compra.getLogin());
		json.put("model", compra.getModel());
		json.put("moneda", compra.getMoneda());
		json.put("monto", compra.getMonto());
		json.put("nombre",compra.getNombre());
		json.put("numbertae", compra.getNumbertae());
		json.put("producto", compra.getProducto());
		json.put("proveedor", compra.getProveedor());
		json.put("userPhone", compra.getUserPhone());
		json.put("userpass",compra.getUserpass());
		json.put("version", compra.getVersion());
		json.put("vigencia", compra.getVigencia());
		return json.toString();
		
	}
	public static TAETransactionResponse  parseJSONTAE(String json) throws JSONException{
		JSONObject parsedJson = new JSONObject (json);
		
		TAETransactionResponse responseTAE = new TAETransactionResponse();
		
		if(parsedJson.getString("codigoError").equals(ConstantsValues.MW_TRANSACTION_STORED_SUCCESS)){
			responseTAE.setCodigoError(ConstantsValues.MW_TRANSACTION_STORED_SUCCESS);
		}else{
			responseTAE.setCodigoError(parsedJson.getString("codigoError"));
		}
			
		
		if(parsedJson.has("folio")){
			responseTAE.setFolio(parsedJson.getString("folio"));
		}else{ 
			responseTAE.setFolio("");
		}		
		responseTAE.setFolioAddcel(parsedJson.getString("folioAddcel"));
		responseTAE.setMensaje(parsedJson.getString("mensaje"));
		responseTAE.setResultado(parsedJson.getString("resultado"));
		
		return responseTAE;
	}
	
/*
 * Method for validate email
 * @param cadena Input email string 
 * */
	
	public static boolean validaCorreo(String cadena){
		String patron = "^[_A-Za-z0-9-\\+\\.]+(\\.[A-Za-z0-9]+)*@[A-Za-z]+(\\.[A-Za-z]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern;
		Matcher matcher;
		
		pattern = Pattern.compile(patron);
		matcher = pattern.matcher(cadena);
		
		if(matcher.matches()){
			return true;
		}else{
			return false;
		}
		
	}
	
	public static  boolean validaURL(String cadena){
			String patron ="^[a-z]+\\:\\/\\/([a-zA-Z0-9\\.\\/]+)+([\\/a-zA-Z0-9]+)*$";
			Pattern pattern;
			Matcher matcher;
			
			pattern = Pattern.compile(patron);
			matcher = pattern.matcher(cadena);
			if(matcher.matches()){
				Log.i(ConstantsValues.TAG_UTILS, "url valida");
				return true;
			}else{
				return false;
				
			}
			
		}
		public static  boolean validaSMTP(String cadena){
			String patron ="^([a-zA-Z0-9\\.]+)*([a-zA-Z0-9]+)*$";
			Pattern pattern;
			Matcher matcher;
			
			pattern = Pattern.compile(patron);
			matcher = pattern.matcher(cadena);
			if(matcher.matches()){
				Log.i(ConstantsValues.TAG_UTILS, "smtp valida");
				return true;
			}else{
				Log.i(ConstantsValues.TAG_UTILS, "smtp mo valida");
				return false;
				
			}
			
		}
	
	
}
